package com.drore.cloud.filter;

import com.drore.cloud.utils.ThreadLocalHolder;
import com.drore.cloud.utils.UUIDUtil;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/***
 * 浙江卓锐科技股份有限公司 版权所有@Copyright 2016
 * 说明
 * 项目名称
 * @since:cloud-ims 1.0
 * @author <a href="mailto:baoec@drore.com">baoec@drore.com </a> 
 * 2018/06/20 12:30
 */

public class GlobalRequestMappingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /***
     * 获取当前请求的Session 统一控制
     * **/
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest) request;
        Cookie[] cookies = request1.getCookies();
        boolean isnew=true;
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("META-SESSION")){
                    ThreadLocalHolder.setSessionId(cookie.getValue());
                    isnew=false;
                }
            }
        }
        if(isnew){
            String redisId = UUIDUtil.getUUID32();
            ThreadLocalHolder.setSessionId(redisId);
            ThreadLocalHolder.setSessionMap(redisId,null);
            Cookie cookie = new Cookie("META-SESSION",redisId);
            cookie.setPath("/");
            HttpServletResponse response1 = (HttpServletResponse) response;
            response1.addCookie(cookie);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

}
